#pragma once
#include <queue>
#include <iostream>
#include <pthread.h>

template <class T>
class BlockQueue
{
    static const int defaultnum = 20;
public:
    BlockQueue(int maxcap = defaultnum)
        : _maxcap(maxcap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
        // lower_water=(_maxcap)/3;
        // higher_water=(_maxcap*2)/3;

    }

    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while (_q.size() == 0) // 等待资源就绪
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        // 1.读取数据 2.被唤醒
        T out = _q.front();
        _q.pop();
        //if (_q.size() < lower_water)
            pthread_cond_signal(&_p_cond); // 唤醒线程

        pthread_mutex_unlock(&_mutex);
        return out;
    }

    void push(const T &in)
    {
        pthread_mutex_lock(&_mutex);

        while (_q.size() == _maxcap)  //while防止线程被伪唤醒
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }

        _q.push(in);
        //if (_q.size() > higher_water)
            pthread_cond_signal(&_c_cond);

        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

private:
    std::queue<T> _q;
    pthread_mutex_t _mutex;
    int _maxcap;
    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;

    // int lower_water;
    // int higher_water;
};